package top.jianx.storage.component;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.jianx.storage.dto.BaseFile;
import top.jianx.storage.factory.StorageTemplateFactory;
import top.jianx.storage.props.StorageProperties;
import top.jianx.storage.template.StorageTemplate;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * 〈执行上传服务器操作〉
 *
 * @author: Jianx
 * @date: 2022/3/20
 * @since: 1.0.0
 */
@Slf4j
@Component
@AllArgsConstructor
@NoArgsConstructor
public class FileComponent {
    @Resource
    StorageProperties properties;
    @Resource
    StorageTemplateFactory templateFactory;

    /**
     * 〈执行上传服务器操作 + 入库记录〉
     *
     * @author: Jianx
     * @date: 2022/3/20
     * @since: 1.0.0
     */
    public BaseFile putFile(InputStream inputStream, String originalFilename, String module, String bucketName) {
        try {
            BaseFile baseFile = getTargetTemplate().putFile(bucketName, module, originalFilename, inputStream);
            log.info("文件上传成功,{}", baseFile.toString());
            return baseFile;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw e;
        }
    }

    /**
     * 获取文件外链
     *
     * @param bucketName 桶名称 {@linkplain String}
     * @param fileName 文件名称 {@linkplain String}
     * @param timeliness 是否设置有效时间内访问文件 {@linkplain String}
     * @return {@linkplain String}
     * @author: Jianx
     * @date: 2022/3/20
     * @since: 1.0.0
     */
    public String fileLink(String bucketName, String fileName, boolean timeliness) {
        return getTargetTemplate().fileLink(fileName, bucketName, timeliness);
    }

    /**
     * 获取文件外链
     *
     * @param bucketName 桶名称 {@linkplain String}
     * @param fileName 文件名称 {@linkplain String}
     * @return {@linkplain String}
     * @author: Jianx
     * @date: 2022/3/20
     * @since: 1.0.0
     */
    public String fileLink(String bucketName, String fileName) {
        return getTargetTemplate().fileLink(fileName, bucketName, properties.getStorageFile().getTimeLines());
    }

    /**
     * 〈获取文件流〉
     *
     * @author: Jianx
     * @date: 2022/3/20
     * @since: 1.0.0
     */
    public InputStream getObject(String bucketName, String fileLink) {
        return getTargetTemplate().getObject(bucketName, fileLink).getInputStream();
    }

    /**
     * 〈获取目标service〉
     *
     * @author: Jianx
     * @date: 2022/3/20
     * @since: 1.0.0
     */
    private StorageTemplate getTargetTemplate() {
        return templateFactory.getInstance(properties.getName());
    }

}
